package com.yun.zf.search.controller;

import com.yun.zf.common.app.domain.ZfCity;
import com.yun.zf.common.utils.DateUtils;
import com.yun.zf.common.vo.Response;
import com.yun.zf.system.exception.CustomException;
import com.yun.zf.system.service.ZfCityService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyEditorSupport;
import java.util.Date;

/**
 * web层通用数据处理
 *
 * @author ruoyi
 */
@Slf4j
public class SearchBaseController {

    @Autowired
    private ZfCityService cityService;

    // 城市处理
    Long aCode = null;
    Long prov = null;

    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder, HttpServletRequest request) {
        String city = request.getHeader("city");
        log.info("头部携带城市信息---------{}", city);
        if (StringUtils.isBlank(city)) {
            throw new CustomException("请选择城市后在进行操作");
        }
        aCode = Long.parseLong(city);
        // 获取省份代码
        ZfCity zfCity = cityService.getCity(aCode);
        prov = zfCity.getPid();

        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport()
        {
            @Override
            public void setAsText(String text)
            {
                setValue(DateUtils.parseDate(text));
            }
        });
    }


    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    protected Response toAjax(int rows) {
        return rows > 0 ? Response.success() : Response.error();
    }
}
